<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>
import { Notification } from "element-ui";
import { mapState } from "vuex";
import { translateGroupSystemNotice } from "../src/utils/common";
import Cookies from "js-cookie";
export default {
  name: "App",
  data() {
    return {
      index: 0,
    };
  },
  methods: {
    getPhoneAddress() {
      this.$api.getSettings.getSettingsList({ cate: "wx" }).then((res) => {
        if (res.data.code == 200 && res.data.status == 1) {
          res.data.result.forEach((item) => {
            if (item.title == "手机端网址") {
              this.$store.commit("setPhoneAddress", item.value);
            }
          });
        } else {
          this.$fnc.alertError(res.data.code_desc, res.data.result);
        }
      });
    },
    getReward() {
      var params = {};
      this.$api.getPlugin.rewardOp(params).then((res) => {
        if (res.data.code == 200) {
          this.$store.commit("setRewardOption", res.data.result);
        }
      });
    },
    getUserInfo() {
      var params = {};
      params.id = localStorage.getItem("adminuid");
      this.$api.getUser.getHeadUserInfo(params).then((res) => {
        if (res.data.code == 200) {
          this.$store.commit("setmanageInfo", res.data.result);
          this.$store.commit("setAdminname", res.data.result.username);
          if (res.data.result.service == 1) {
            var obj = {};
            if (res.data.result.sig) {
              obj.userID = res.data.result.sig.identifier;
              obj.userSig = res.data.result.sig.userSig;
              this.$store.dispatch("login", obj);
            }
          }
          this.$store.commit("setisnotice", res.data.result.is_notice);
          this.$store.commit("setisservice", res.data.result.service);
        }
      });
    },
    initListener() {
      // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
      this.tim.on(this.TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this);
      // SDK NOT READT
      this.tim.on(this.TIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this);
      // 被踢出
      this.tim.on(this.TIM.EVENT.KICKED_OUT, ({ data: { type } }) => {
        const message = type === this.TIM.TYPES.KICKED_OUT_MULT_ACCOUNT ? "您的账号已在其他页面登录" : "您的账号已在其他设备登录";
        this.$message.error(message);
        this.$store.commit("toggleIsLogin", false);
        this.$store.commit("reset");
      });
      // SDK内部出错
      this.tim.on(this.TIM.EVENT.ERROR, this.onError);
      // 收到新消息
      this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage);
      // 会话列表更新
      this.tim.on(this.TIM.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
        this.$store.commit("updateConversationList", event.data);
      });
      // 群组列表更新
      this.tim.on(this.TIM.EVENT.GROUP_LIST_UPDATED, (event) => {
        this.$store.commit("updateGroupList", event.data);
      });
      // 收到新的群系统通知
      this.tim.on(this.TIM.EVENT.GROUP_SYSTEM_NOTICE_RECEIVED, (event) => {
        const isKickedout = event.data.type === 4;
        const isCurrentConversation = `GROUP${event.data.message.payload.groupProfile.groupID}` === this.currentConversation.conversationID;
        // 在当前会话被踢，需reset当前会话
        if (isKickedout && isCurrentConversation) {
          this.$store.commit("resetCurrentConversation");
        }
        Notification({
          title: "新系统通知",
          message: translateGroupSystemNotice(event.data.message),
          duration: 3000,
          onClick: () => {
            const SystemConversationID = "@TIM#SYSTEM";
            this.$store.dispatch("checkoutConversation", SystemConversationID);
          },
        });
      });
    },
    onReceiveMessage({ data: messageList }) {
      messageList.forEach((item) => {
        if (item.conversationType == "GROUP" && item.ID.indexOf("GROUP@TGS") >= 0) {
          this.tim.setMessageRead({
            conversationID: item.conversationID,
          });
          if (item.elements[0].content.data == "present") {
            this.$store.commit("addLivePresent", [item]);
            this.$store.commit("addLiveMsg", [item]);
          } else {
            this.$store.commit("addLiveMsg", [item]);
          }
        }
      });
      let sound = new Audio();
      sound.src = "http://downsc.chinaz.net/Files/DownLoad/sound1/201607/7499.mp3";
      sound.play();
      this.handleAt(messageList);
      this.$store.commit("pushCurrentMessageList", messageList);
    },
    onError({ data: error }) {
      // this.$message.error(error.message)
    },
    onReadyStateUpdate({ name }) {
      const isSDKReady = name === this.TIM.EVENT.SDK_READY ? true : false;

      this.$store.commit("toggleIsSDKReady", isSDKReady);
      if (isSDKReady) {
        this.tim.getMyProfile().then(({ data }) => {
          this.$store.commit("updateCurrentUserProfile", data);
        });
        this.$store.dispatch("getBlacklist");
      }
    },
    /**
     * 处理 @ 我的消息
     * @param {Message[]} messageList
     */
    handleAt(messageList) {
      // 筛选有 @ 符号的文本消息
      const atTextMessageList = messageList.filter((message) => message.type === this.TIM.TYPES.MSG_TEXT && message.payload.text.includes("@"));
      for (let i = 0; i < atTextMessageList.length; i++) {
        const message = atTextMessageList[i];
        const matched = message.payload.text.match(/@\w+/g);
        if (!matched) {
          continue;
        }
        // @ 我的
        if (matched.includes(`@${this.currentUserProfile.userID}`)) {
          // 当前页面不可见时，调用window.Notification接口，系统级别通知。
          if (document.hidden) {
            this.notifyMe(message);
          }
          Notification({
            title: `有人在群${message.conversationID.slice(5)}提到了你`,
            message: message.payload.text,
            duration: 3000,
          });
          this.$bus.$emit("new-messsage-at-me", {
            data: { conversationID: message.conversationID },
          });
        }
      }
    },
    /**
     * 使用 window.Notification 进行全局的系统通知
     * @param {Message} message
     */
    notifyMe(message) {
      // 需检测浏览器支持和用户授权
      if (!("Notification" in window)) {
        return;
      } else if (window.Notification.permission === "granted") {
        this.handleNotify(message);
      } else if (window.Notification.permission !== "denied") {
        window.Notification.requestPermission().then((permission) => {
          // 如果用户同意，就可以向他们发送通知
          if (permission === "granted") {
            this.handleNotify(message);
          }
        });
      }
    },
    handleNotify(message) {
      const notification = new window.Notification("有人提到了你", {
        body: message.payload.text,
      });
      notification.onclick = () => {
        window.focus();
        this.$store.dispatch("checkoutConversation", message.conversationID);
        notification.close();
      };
    },
  },
  components: {},
  beforeCreate() {},
  created() {
    this.$store.commit("setIsLoading", false);
    const uid = localStorage.getItem("adminuid") || "";
    const admin_key = localStorage.getItem("admin_key") || "";
    if (uid && admin_key) {
      this.getReward();

      this.getUserInfo();
      this.$store.dispatch("getHeadInfo");
      this.$store.dispatch("getMenu");
      //getMailOpen

      this.$store.dispatch("getMailOpen");
      this.$store.dispatch("getPlugin");
    } else if (location.href.indexOf("plugin-index") >= 0) {
      this.$router.push("/plugin-index");
    } else {
      console.log(222);
      this.$router.push("/login");
    }

    localStorage.getItem("store") && this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(localStorage.getItem("store"))));
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", (e) => {
      localStorage.setItem("store", JSON.stringify(this.$store.state));
    });
  },
  watch: {
    $route(to) {
      if (this.$store.state.adminTitle) {
        document.title = this.$store.state.adminTitle;
      }
      var adminuid = Cookies.get("adminuid") || "";
      if (adminuid) {
        if (this.$store.state.ratting.length == 0) {
          this.$store.dispatch("getRatting");
        }
        if (this.$store.state.phoneAddress == "") {
          this.getPhoneAddress();
        }
      }
      this.$store.commit("setIsLoading", false);
      if (JSON.stringify(this.$store.state.plugin) == "{}") {
        this.$store.dispatch("getPlugin");
      }

      var obj = this.$store.state.menuList;
      var path = this.$route.fullPath;
      const admin_key = localStorage.getItem("admin_key") || "";
      const uid = localStorage.getItem("adminuid") || "";
      if (path.indexOf("/login") == -1 && obj == "" && uid != "" && admin_key != "" && path.indexOf("plugin-index") == -1) {
        this.getUserInfo();
        this.$store.dispatch("getMenu");
      }
      if (path != "/redirect" && path.indexOf("/login") == -1 && path.indexOf("plugin-index") == -1) {
        console.log(path);
        for (var i in obj) {
          if (typeof obj[i].z == "object" && obj[i].z.length > 0 && (path == obj[i].url || path == obj[i].z[0].url)) {
            this.$store.commit("setParentTtile", obj[i].title);
            sessionStorage.setItem("parentTitle", obj[i].title);
            this.$store.commit("setTitle", obj[i].z[0].title);
            sessionStorage.setItem("title", obj[i].z[0].title);
            if (obj[i].z[0].z) {
              this.$store.commit("setTitle2", obj[i].z[0].z[0].title);
              this.$store.commit("showTitle2", true);
            }
            break;
          }
        }
      }
    },
  },
  computed: {
    ...mapState({
      currentUserProfile: (state) => state.user.currentUserProfile,
      currentConversation: (state) => state.conversation.currentConversation,
      isLogin: (state) => state.user.isLogin,
      isSDKReady: (state) => state.user.isSDKReady,
    }),
    getMenu() {
      return this.$store.state.menuList;
    },
  },
  mounted() {
    // 初始化监听器
    this.initListener();
    window.vue = this;
    if (sessionStorage.getItem("parentTitle")) {
      this.$store.commit("setParentTtile", sessionStorage.getItem("parentTitle"));
      this.$store.commit("setTitle", sessionStorage.getItem("title"));
    }
  },
};
</script>
<style lang="less">
@font-face {
  font-family: "gilroy";
  src: url("./assets/fonts/gilroy-regular.otf");
}

#app {
  font-family: "gilroy", "微软雅黑", "Avenir";
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  // height: 100%;
  display: flex;
  // overflow: auto;
  height: 100%;
}
</style>
